package com.zbs.framework.swagger.utils;

import com.zbs.framework.swagger.config.SwaggerBusinessRuntimeException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Configuration
@ConfigurationProperties("spring.datasource")
public class JdbcUtils {

    private String url;
    private String driverClassName;
    private String username;
    private String password;

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDBName() {
        String dbName = "";
        try {
            if (StringUtils.hasLength(this.url)) {
                String reg = "/(.*?)\\?";
                Pattern p = Pattern.compile(reg);
                Matcher m = p.matcher(this.url);
                if (m.find()) {
                    String replace = m.group();
                    dbName = replace.substring(replace.lastIndexOf("/")+1,replace.indexOf("?"));
                }
                if (!StringUtils.hasLength(dbName)){
                    throw new SwaggerBusinessRuntimeException(-1, "还未配置数据源，解析失败");
                }
            } else {
                throw new SwaggerBusinessRuntimeException(-1, "还未配置数据源，解析失败");
            }
        } catch (Exception e) {
            throw new SwaggerBusinessRuntimeException(-1, "数据库url异常，解析失败");
        }

        return dbName;
    }

    public DataSource getDataSource() {
        DriverManagerDataSource source = new DriverManagerDataSource();
        source.setDriverClassName(this.driverClassName);
        source.setUrl(this.url);
        source.setUsername(this.username);
        source.setPassword(this.password);
        return source;

    }

    ;
}